<?php
// Usage: <a href="download.php?file=test.txt&category=test">Download</a>  
// Path to downloadable files (will not be revealed to users so they will never know your file's real address)

//sample_id
//file_type
//file_id

session_start();
if (!$_SESSION['auth']) {
	echo "Please <a href=\"../login_form.php\">log in</a> to the MoDD website.";
	
	die();
}


$samples_path = "/home/moddwebc/public_html/samples/";

if (empty($_GET['file_id']) or empty($_GET['file_type']) or empty($_GET['sample_id'])) {
	echo ("Missing information");
	die();
}

$file_type = $_GET['file_type'];



$file_path = "";

switch($file_type){
	case "mp3":     
		$file_path = $samples_path . "sample_" . 
					$_GET['sample_id'] . "/audio/audio_" . $_GET['file_id'] . 
					"." . $file_type ;                
		break;
	case "amr":     
		$file_path = $samples_path . "sample_" . 
					$_GET['sample_id'] . "/audio/audio_" . $_GET['file_id'] . 
					"." . $file_type ;                
		break;
	case "jpg":     
		$file_path = $samples_path . "sample_" . 
					$_GET['sample_id'] . "/image/image_" . $_GET['file_id'] . 
					"." . $file_type ;                
		break;
}

if (strcmp($file_path,"") == 0) {
	echo "Couldn't find file.";
	die;
}

// Check to see if the download script was called
if (basename($_SERVER['PHP_SELF']) == 'get_file.php'){
    if ($_SERVER['QUERY_STRING'] != null){
        
        // If requested file exists
        if (file_exists($file_path)){
            
            // Determine correct MIME type
            switch($file_type){
                case "mp3":     $type = "audio/mpeg";                    break;
                case "jpg":     $type = "image/jpeg";	                 break;
                case "amr":     $type = "audio/amr"; 					 break;
            }
           
            // Prepare headers
            //header("Pragma: public");
            //header("Expires: 0");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Cache-Control: public", false);
            //header("Content-Description: File Transfer");
            header("Content-Type: " . $type);
            header("Accept-Ranges: bytes");
            //header("Content-Disposition: attachment; filename=\"sample." . $file_type . "\";");
            header("Content-Transfer-Encoding: binary");
            header("Content-Length: " . filesize($file_path));
            // Send file for download
            if ($stream = fopen($file_path, 'rb')){
                while(!feof($stream) && connection_status() == 0){
                    //reset time limit for big files
                    set_time_limit(0);
                    print(fread($stream,1024*8));
                    flush();
                }
                fclose($stream);
            }
        }
		
		else{
            // Requested file does not exist (File not found)
            echo("Requested file (".$file_path.") does not exist");
            die();
        }
    }
}
?>